package com.wcy.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wcy.annotation.aop.PreAuth;
import com.wcy.entity.UserLearningHistory;
import com.wcy.entity.pageVo.ApiDescriptor;
import com.wcy.entity.pageVo.ColumnConstructor;
import com.wcy.entity.pageVo.PageData;
import com.wcy.entity.queryVo.QueryConvertor;
import com.wcy.service.IUserLearningHistoryService;
import com.wcy.util.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/userLearningHistory")
public class UserLearningHistoryController {

    @Autowired
    private IUserLearningHistoryService userLearningHistoryService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PreAuth("HISTORY:QUERY")
    @GetMapping("/page")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Page<UserLearningHistory>> getPage(@RequestParam(defaultValue = "1") int pageNum,
                                                             @RequestParam(defaultValue = "10") int pageSize,
                                                             HttpServletRequest request) {
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData).convert(true);
        Page<UserLearningHistory> page = userLearningHistoryService.page(new Page<>(pageNum, pageSize),wrapper);
        return ResponseEntity.ok(page);
    }

//    @PreAuth("HISTORY:QUERY")
    @GetMapping("/list")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<List<UserLearningHistory>> getList(HttpServletRequest request) {
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData).convert(true);
        List<UserLearningHistory> list = userLearningHistoryService.list(wrapper);
        return ResponseEntity.ok(list);
    }

    @PreAuth("HISTORY:ADD")
    @PostMapping("/add")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> add(@RequestBody UserLearningHistory userLearningHistory) {
        userLearningHistory.setAccessedAt(LocalDateTime.now());
        userLearningHistoryService.save(userLearningHistory);
        return ResponseEntity.ok().build();
    }

    @PreAuth("HISTORY:ALTER")
    @PutMapping("/update")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> update(@RequestBody UserLearningHistory userLearningHistory) {
        userLearningHistoryService.updateById(userLearningHistory);
        return ResponseEntity.ok().build();
    }

    @PreAuth("HISTORY:DELETE")
    @DeleteMapping("/delete/{id}")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> delete(@PathVariable Integer id) {
        userLearningHistoryService.removeById(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/sendHistory")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> sendHistory(@RequestBody UserLearningHistory userLearningHistory,HttpServletRequest request) {
        Integer id = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        userLearningHistory.setUserId(id);
        userLearningHistory.setAccessedAt(LocalDateTime.now());
        userLearningHistoryService.save(userLearningHistory);
        return ResponseEntity.ok().build();
    }

    @GetMapping("user/page")
    public ResponseEntity<Page<UserLearningHistory>> getUserHistoryPage(@RequestParam(name = "pageNum",defaultValue = "1") int pageNum,
                                                                            @RequestParam(name = "pageSize",defaultValue = "10") int pageSize,
                                                                        HttpServletRequest request){
        Integer userId = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData,true).convert(true);
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("accessed_at");
        return ResponseEntity.ok(userLearningHistoryService.page(Page.of(pageNum,pageSize),wrapper));
    }

    @DeleteMapping("user/delete/{id}")
    public ResponseEntity<Void> deleteHistory(@PathVariable("id") Integer id,HttpServletRequest request) {
        Integer userId = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        if (Objects.equals(userLearningHistoryService.getById(id).getUserId(), userId)) {
            userLearningHistoryService.removeById(id);
        }
        return ResponseEntity.ok().build();
    }

    @GetMapping("/user/sum")
    public ResponseEntity<Long> getSumLearningTime(HttpServletRequest request) {
        Integer userId = jwtTokenUtil.getUserIdFromToken(jwtTokenUtil.getToken(request));
        return ResponseEntity.ok(userLearningHistoryService.list(new QueryWrapper<UserLearningHistory>().eq("user_id", userId)).stream().mapToLong(UserLearningHistory::getStudyDuration).sum());
    }
}